package logic

import (
	"context"
	"fmt"
	"muke-chain/models/cache"
	"muke-chain/models/mysql"
	"muke-chain/mukerpc/internal/svc"
	"muke-chain/mukerpc/mukerpc"
	"muke-chain/pkg"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginUserLogic {
	return &LoginUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginUserLogic) LoginUser(in *mukerpc.LoginUserRequest) (*mukerpc.LoginUserResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.Rdb.Get(l.ctx, "sendSms"+"login"+in.Mobile)
	if get.Val() != in.Sms {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	var user mysql.Users
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该号未注册,请前往注册")
	}

	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码错误,请重新输入")
	}

	cache.Rdb.Del(l.ctx, "sendSms"+"login"+in.Mobile)

	return &mukerpc.LoginUserResponse{Id: int64(user.ID)}, nil
}
